<?php

/**
 * @Author: Wang Chunsheng 2192138785@qq.com
 * @Date:   2020-03-10 20:37:35
 * @Last Modified by:   Wang Chunsheng 2192138785@qq.com
 * @Last Modified time: 2020-03-16 16:26:32
 */


namespace api\modules\diandi_shop\services;

use Yii;
use app\modules\diandi_shop\models\DdGoods;
use common\helpers\ImageHelper;
use common\services\BaseService;
use yii\data\Pagination;

class GoodsService extends BaseService
{
    const INACTIVE = 0;
    const ACTIVE = 10;
    /**
     * 获取商品列表
     * 默认分页参数为page
     * @param int|null post
     * @return string
     * @throws NotFoundHttpException
     */
    public static function getList($category_pid = 0, $category_id = 0, $keywords = '', $pageSize = 10)
    {
        $page = Yii::$app->request->get('page');
        $keys = 'goodsinfo_' . $category_pid . $category_id . $page;
        // if (Yii::$app->cache->get($keys)) { //如果有缓存数据则返回缓存数据，没有则从数据库取病存入缓存中

        //     return Yii::$app->cache->get($keys);
        // } else {
        $where = []; //初始化条件数组
        if (!empty($category_pid)) {
            $where['category_pid'] = $category_pid;
        }
        if (!empty($category_id)) {
            $where['category_id'] = $category_id;
        }
        if (!empty($keywords)) {
            $where['keywords'] = ['like', $keywords];
        }
        // 创建一个 DB 查询来获得所有
        $query = DdGoods::find()->where($where);
        // 得到文章的总数（但是还没有从数据库取数据）
        $count = $query->count();
        // 'pageSize' => 10,'pageSizeParam'=>false.............]);中的参数
        // 'totalCount' 为数据总数
        // 'pageSize' 为每页显示数
        // 'pageSizeParam'=>false, 可将分页路径中per-page参数隐藏去掉
        // 'pageParam' => 'p', 可更改分页url中分页参数name名称
        // 'route' => false, 当分页在于首页时隐藏掉路由，将/site/index?p=1变为/?p=1
        // 'validatePage' => false, 取消分页验证,当手动输入page=20时不再跳到page=1
        // 使用总数来创建一个分页对象
        $pagination = new Pagination([
            'totalCount' => $count,
            'pageSize' => $pageSize
        ]);
        $list = $query->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        foreach ($list as &$item) {
            $item['thumb'] = ImageHelper::tomeia($item['thumb']);
            $images = unserialize($item['images']);
            $item['images'] = ImageHelper::tomeia($images);
        }
        Yii::$app->cache->set($keys, $list, 3600);

        return $list;
        // }
    }
}
